package com.wechat.back.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wechat.back.mapper.UserMapper;
import com.wechat.back.pojo.tools.PageBean;
import com.wechat.back.pojo.User;
import com.wechat.back.service.UserService;
import com.wechat.back.utils.Md5Util;
import com.wechat.back.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User findByUserName(String username) {
        User u = userMapper.findByUserName(username);
        return u;
    }

    @Override
    public void register(String username, String password, Integer userPower) {
        //加密
        String md5String = Md5Util.getMD5String(password);
        //添加
        userMapper.add(username, md5String, userPower);
    }
    //更新
    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    //更新用户状态
    @Override
    public void updateStatus(String userStatus) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateStatus(id,userStatus);
        System.out.println("userStatus:"+userStatus);
    }
    //更新用户权限
    @Override
    public void updatePower(Integer id, Integer userPower) {
        userMapper.updatePower(id,userPower);
    }

    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl, id);
    }

    @Override
    public void updatePwd(Integer id,String newPwd) {
        userMapper.updatePwd(Md5Util.getMD5String(newPwd),id);
    }

    @Override
    public PageBean<User> list(Integer pageNum, Integer pageSize ,String username) {
        //1.创建PageBean对象
        PageBean<User> pb = new PageBean<>();
        //2.开启分页查询 PageHelper
        PageHelper.startPage(pageNum,pageSize);
        //调用mapper
        List<User> users = userMapper.list(username);
        Page<User> u = (Page<User>) users;

        pb.setTotal(u.getTotal());
        pb.setItems(u.getResult());

        return pb;
    }

    @Override
    public User findById(Integer id) {
        User u = userMapper.findById(id);
        return u;
    }
}
